﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;

namespace mal.Web.Silverlight.MEF.Core.ContentLoader
{
    /// <summary>
    /// Represents the status of the asynchronous loading module
    /// </summary>
    public class ContentLoaderBaseAsyncResult : IAsyncResult
    {
        public ContentLoaderBaseAsyncResult(object asyncState, LoaderBase loader, AsyncCallback callback)
        {
            this.AsyncState = asyncState;
            this.Loader = loader;
            this.Lock = new object();
            this.Callback = callback;
            AsyncWaitHandle = new AutoResetEvent(false);
        }

        /// <summary>
        /// Object that load the page requested
        /// </summary>
        internal LoaderBase Loader { get; private set; }        
        internal AsyncCallback Callback { get; private set; }
        internal Exception Error { get; set; }

        /// <summary>
        /// Page requested
        /// </summary>
        internal object Page { get; set; }
        internal Uri RedirectUri { get; set; }
        internal object Lock { get; private set; }
        internal bool BeginLoadCompleted { get; set; }

        #region IAsyncResult Members
        /// <summary>
        /// Gets a user-defined object that qualifies or contains information about an asynchronous operation.
        /// </summary>
        public object AsyncState
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a WaitHandle that is used to wait for an asynchronous operation to complete.
        /// </summary>
        public System.Threading.WaitHandle AsyncWaitHandle
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a value that indicates whether the asynchronous operation completed synchronously.
        /// </summary>
        public bool CompletedSynchronously
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a value that indicates whether the asynchronous operation has completed.
        /// </summary>
        public bool IsCompleted
        {
            get;
            private set;
        }

        public void Complete()
        {
            this.CompletedSynchronously = !BeginLoadCompleted;
            this.IsCompleted = true;
            (this.AsyncWaitHandle as AutoResetEvent).Set();
        }

        #endregion
    }
}
